package com.jhgsys.internal.monitor.service.impl;

import com.jhgsys.internal.monitor.service.IEhcacheService;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EhcacheServiceImpl implements IEhcacheService {

    @Autowired
    private CacheManager cacheManager;

    private static final String DEFAULT_CACHE = "users";

    @Override
    public String get(String key) {
        return get(DEFAULT_CACHE, key);
    }

    @Override
    public String set(String key, String value) {
        return set(DEFAULT_CACHE, key, value);
    }

    @Override
    public String set(String key, String value, int second) {
        return set(DEFAULT_CACHE, key, value, second);
    }

    /**
     * 判断是否存在KEY
     * @param key
     * @return
     */
    @Override
    public boolean hasKey(String key) {
        return (get(key) != null);
    }

    /**
     * 更新key的过期时间
     * @param key
     * @param second 超时时间
     */
    @Override
    public void expire(String key, int second) {
        Cache cache = cacheManager.getCache(DEFAULT_CACHE);
        Element value = cache.get(key);
        if (value == null) {
            Element element = new Element(key, "");
            element.setTimeToLive(second);
            cache.put(element);
        } else {
            Element element = new Element(key, value.getObjectValue(), value.getVersion());
            element.setTimeToLive(second);
            cache.replace(value, element);
        }
    }

    @Override
    public String get(String cacheName, String key) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            return null;
        }
        Element value = cache.get(key);
        if (value == null) {
            return null;
        }
        Object o = value.getObjectValue();
        if (o == null) {
            return null;
        }
        return o.toString();
    }

    @Override
    public String set(String cacheName, String key, String value) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            return null;
        }
        Element element = new Element(key, value);
        cache.put(element);
        return value;
    }

    @Override
    public String set(String cacheName, String key, String value, int second) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            return null;
        }
        Element element = new Element(key, value);
        element.setTimeToLive(second);
        cache.put(element);
        return value;
    }
}
